package com.lhz.framework.manager.threadManager.factory;

import com.lhz.common.utils.ServletUtils;
import com.lhz.framework.manager.threadManager.BaseThreadManager;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Constructor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步工厂（产生任务用）
 * @author LiGezZ
 */
@Slf4j
public class AsyncFactory {

    private AsyncBean asyncBean;

    public AsyncFactory(AsyncBean asyncBean) {
        this.asyncBean = asyncBean;
    }

    public AsyncBean getThread() {
        return asyncBean;
    }

    public void setAsyncBean(AsyncBean asyncBean) {
        this.asyncBean = asyncBean;
    }

    /**
     * 执行线程代码
     *
     * @param threadPool
     */
    public void execute(ThreadPoolExecutor threadPool) {
        try {
            HttpServletRequest request = ServletUtils.getRequest();
            Constructor<?> constructor = asyncBean.getThreadManagerClass().getConstructor(AsyncBean.class, Object.class);
            BaseThreadManager runnable = (BaseThreadManager) constructor.newInstance(asyncBean, request);
            threadPool.execute(runnable);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
